package com.example.studykotlin.kotlin_actual_combat.art.aidl.custom;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.example.studykotlin.Path;
import com.example.studykotlin.databinding.ActivityMyBookManagerBinding;
import com.example.studykotlin.kotlin_actual_combat.art.aidl.Book;
import com.example.studykotlin.kotlin_actual_combat.art.aidl.BookMangerService;
import com.example.studykotlin.kotlin_actual_combat.art.aidl.IOnNewBookArrivedListener;

import java.util.List;
@Route(path = Path.my_bookManager)
public class MyBookManagerActivity extends AppCompatActivity {
    private ActivityMyBookManagerBinding binding;
    private static final String TAG = "MyBookManagerActivity";
    private IMyBookManager myBookManager;
    private static final int MESSAGE_NEW_BOOK_ARRIVED = 1;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case MESSAGE_NEW_BOOK_ARRIVED:
                    Log.e(TAG, "receive new book:"+ msg.obj );
                    break;
                default:
                    super.handleMessage(msg);
                    break;
            }
        }
    };

    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            myBookManager = MyBookManagerImpl.asInterface(service);
            try {
                service.linkToDeath(mDeathRecipient,0);
                List<Book> list = myBookManager.getBookList();
                Log.e(TAG, "query book list"+list);
                Book book = new Book(3,"Android开发艺术探索");
                myBookManager.addBook(book);
                Log.e(TAG, "add Book"+book);
                List<Book> newList = myBookManager.getBookList();
                Log.e(TAG, "query book list"+newList);
                myBookManager.registerListener(onNewBookArrivedListener);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            //重新绑定远程Service,注意不能耗时
            Intent intent = new Intent(MyBookManagerActivity.this, BookMangerService.class);
            bindService(intent,mConnection, Context.BIND_AUTO_CREATE);
        }
    };

    private IBinder.DeathRecipient mDeathRecipient = new IBinder.DeathRecipient() {
        @Override
        public void binderDied() {
            Log.e(TAG, "binder died. tname:" + Thread.currentThread().getName());
            if (myBookManager != null) return;
            myBookManager.asBinder().unlinkToDeath(mDeathRecipient,0);
            myBookManager = null;
            //重新绑定远程Service
            Intent intent = new Intent(MyBookManagerActivity.this, BookMangerService.class);
            bindService(intent,mConnection, Context.BIND_AUTO_CREATE);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMyBookManagerBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        Intent intent = new Intent(this,MyBookManagerService.class);
        bindService(intent,mConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onDestroy() {
        if (myBookManager != null && myBookManager.asBinder().isBinderAlive()) {
            Log.e(TAG, "unregister listener:"+onNewBookArrivedListener );
            try {
                myBookManager.unregisterListener(onNewBookArrivedListener);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        unbindService(mConnection);
        super.onDestroy();
    }

    private IOnNewBookArrivedListener onNewBookArrivedListener = new IOnNewBookArrivedListener.Stub() {
        @Override
        public void onNewBookArrived(Book book) throws RemoteException {
            mHandler.obtainMessage(MESSAGE_NEW_BOOK_ARRIVED,book).sendToTarget();
        }
    };
}